package com.example.ctrip.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.ctrip.commons.CommonResult;
import com.example.ctrip.entity.ReturnAjax;
import com.example.ctrip.entity.StepReturn;
import com.example.ctrip.plugs.payFlight;
import com.example.ctrip.service.IPAddrsService;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.Map;

import static com.example.ctrip.commons.CommWebTools.getWebDriver;

@RestController
@RequestMapping("/doFlow")
public class DoFlowController {
    private final Logger logger = LoggerFactory.getLogger(DoFlowController.class);

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    IPAddrsService ipAddrsService;

    private final static int reTryTimes = 5;

    @PostMapping("/doFlow")
    public ReturnAjax doFlow(@RequestBody Map<String, String> map) {
        ReturnAjax ret = null;
        try {
            String plugName = map.get("plugName");
            Class clazz = Class.forName(plugName);
            System.out.println("plugName=================================="+plugName);
            System.out.println("map======================================="+map.toString());

            Constructor con = clazz.getConstructor(Map.class, WebDriver.class);
            WebDriver webDriver = getWebDriver(map.get("IP"));
            System.out.println("1");
            Object obj = con.newInstance(map, webDriver);
            System.out.println("2");
            //开始走流程，从step0开始......
            int step = 0;
            int reTry = 0;
            Method m = clazz.getMethod("Step" + step, new Class<?>[]{});
            StepReturn stepret = (StepReturn) m.invoke(obj, new Object[]{});
            while (stepret.getRetCode() == 0 || stepret.getRetCode() == 1) {
                //返回0需要刷新页面再试且判断是否超过重试次数，如超过则返回失败
                //返回1代表正常返回，进入下一步
                switch (stepret.getRetCode()) {
                    case 0:
                        if (reTry > reTryTimes) {
                            if (m.getName().equals("Step6")){
                                JSONObject paramJson = JSONObject.parseObject(map.get("DETAILS"));
                                payFlight.orderRk(paramJson.getString("ddbh"), "{'code':'1','msg':'创建订单失败'}", "10");
                            }
                            //返回失败，某一页面超过重试次数，重新更换代理IP
                            return new ReturnAjax(CommonResult.CHANGE_PROXY_IP.getCode(), CommonResult.CHANGE_PROXY_IP.getStatus(), CommonResult.CHANGE_PROXY_IP.getMsg(), stepret.getResponse());
                        }else {
                            reTry++;
                            webDriver.navigate().refresh();
                            //等2秒刷新
                            Thread.sleep(2000);
                        }
                        break;
                    case 1:
                        //重置重试次数，让下一个步骤出错后，也能重试多次
                        reTry = 0;
                        //继续下个步骤
                        step++;
                }
                m = clazz.getMethod("Step" + step, new Class<?>[]{});
                stepret = (StepReturn) m.invoke(obj, new Object[]{});
            }
            switch (stepret.getRetCode()) {
                case 2:
                    //2网络报错重新更换代理IP
                    ret = new ReturnAjax(CommonResult.CHANGE_PROXY_IP.getCode(), CommonResult.CHANGE_PROXY_IP.getStatus(), CommonResult.CHANGE_PROXY_IP.getMsg(), stepret.getResponse());
                    break;
                case 3:
                    //3任务报错无法执行
                    ret = new ReturnAjax(CommonResult.TASK_FAILED.getCode(), CommonResult.TASK_FAILED.getStatus(), CommonResult.TASK_FAILED.getMsg(), stepret.getResponse());
                    break;
                case 4:
                    //4所有步骤执行完毕
                    ret = new ReturnAjax(CommonResult.SUCCESS.getCode(), CommonResult.SUCCESS.getStatus(), CommonResult.SUCCESS.getMsg(), stepret.getResponse());
            }
        } catch (Exception e) {
            logger.info(e.toString());
            e.printStackTrace();
            ret = new ReturnAjax(CommonResult.TASK_FAILED.getCode(), CommonResult.TASK_FAILED.getStatus(), CommonResult.TASK_FAILED.getMsg(), "DoFlow Exception报错:" + e.getMessage());
        }
        return ret;
    }
}
